package main

import (
	"chapter-200-etcd/service"
	"log"

	// 标准库
	"context"
	"encoding/json"
	"flag"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/grpclog"
	"net"
	"time"

	// etcd
	eclient "go.etcd.io/etcd/client/v3"
	"go.etcd.io/etcd/client/v3/naming/endpoints"

	clientv3 "go.etcd.io/etcd/client/v3"
)

var (
	// MyService grpc 服务名
	MyService = "xiaoxu/demo"
)

type server struct {
	service.UnimplementedActionServer
}

func (*server) SayHello(ctx context.Context, req *service.HelloRequest) (*service.HelloResponse, error) {
	marshal, _ := json.Marshal(req)
	grpclog.Info("收到 Grpc 请求,args", string(marshal))
	return &service.HelloResponse{
		Name: "yangchao",
		Age:  "18",
	}, nil
}

func main() {
	// 接收命令行指定的 grpc 服务端口
	var port int
	flag.IntVar(&port, "port", 8080, "port")
	flag.Parse()
	addr := fmt.Sprintf("localhost:%d", port)
	// 创建 tcp 端口监听器
	listener, err := net.Listen("tcp", ":8080")
	if err != nil {
		fmt.Printf("Failed to listen: %v\n", err)
		return
	}
	// 创建 grpc server
	grpcServer := grpc.NewServer()
	service.RegisterActionServer(grpcServer, &server{})
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	// 注册 grpc 服务节点到 etcd 中
	go registerEndPointToEtcd(ctx, addr)
	// 启动 grpc 服务
	if err := grpcServer.Serve(listener); err != nil {
		fmt.Println(err)
	}
}

func registerEndPointToEtcd(ctx context.Context, addr string) {
	fmt.Println("注册 grpc")
	// 创建 etcd 客户端
	etcdClient, err := clientv3.New(clientv3.Config{
		Endpoints:   []string{"192.168.10.20:2379"},
		DialTimeout: 5 * time.Second,
	})
	if err != nil {
		log.Fatal(err)
	}
	etcdManager, err := endpoints.NewManager(etcdClient, MyService)
	if err != nil {
		log.Fatal(err)
	}
	// 创建一个租约，每隔 10s 需要向 etcd 汇报一次心跳，证明当前节点仍然存活
	var ttl int64 = 10
	lease, err := etcdClient.Grant(ctx, ttl)
	if err != nil {
		log.Fatal(err)
	}
	// 添加注册节点到 etcd 中，并且携带上租约 id
	err = etcdManager.AddEndpoint(ctx, fmt.Sprintf("%s/%s", MyService, addr), endpoints.Endpoint{Addr: addr}, eclient.WithLease(lease.ID))
	if err != nil {
		grpclog.Errorf("register endpoint err: %v", err)
	}
	// 每隔 5 s进行一次延续租约的动作
	for {
		select {
		case <-time.After(5 * time.Second):
			// 续约操作
			resp, _ := etcdClient.KeepAliveOnce(ctx, lease.ID)
			fmt.Printf("keep alive resp: %+v\n", resp)
		case <-ctx.Done():
			return
		}
	}
}
